const request = require('./request.js').default;

/**
 * 徽章相关 API
 */
const badgeAPI = {
  /**
   * 获取所有徽章定义
   */
  getAllBadges: () => request('/badge/all', 'GET'),

  /**
   * 根据分类获取徽章定义
   * @param {string} category - 徽章分类
   */
  getBadgesByCategory: (category) => request(`/badge/category/${category}`, 'GET'),

  /**
   * 获取当前用户的徽章列表
   */
  getMyBadges: () => request('/badge/my-badges', 'GET'),

  /**
   * 获取指定用户的徽章列表
   * @param {number} userId - 用户ID
   */
  getUserBadges: (userId) => request(`/badge/user/${userId}`, 'GET'),

  /**
   * 获取徽章详情
   * @param {number} badgeId - 徽章ID
   */
  getBadgeDetail: (badgeId) => request(`/badge/${badgeId}`, 'GET'),

  /**
   * 设置徽章显示状态
   * @param {number} badgeId - 徽章ID
   * @param {boolean} isVisible - 是否显示
   */
  setBadgeVisibility: (badgeId, isVisible) => request(`/badge/${badgeId}/visibility`, 'PUT', null, { isVisible }),

  /**
   * 获取当前用户徽章数量统计
   */
  getMyBadgeCount: () => request('/badge/count', 'GET'),

  /**
   * 获取指定用户的徽章数量统计
   * @param {number} userId - 用户ID
   */
  getUserBadgeCount: (userId) => request(`/badge/count/${userId}`, 'GET'),


  /**
   * 获取用户徽章墙数据（灵曜页面专用）
   * @param {number} userId - 用户ID（可选，不传则获取当前用户）
   */
  getBadgeWall: (userId) => {
    if (userId) {
      return request(`/badge/user/${userId}`, 'GET');
    } else {
      return request('/badge/my-badges', 'GET');
    }
  },

  /**
   * 获取徽章分类列表
   */
  getBadgeCategories: () => request('/badge/all', 'GET').then(res => {
    const categories = [...new Set(res.data.map(badge => badge.category))];
    return { code: 200, data: categories };
  }),

  /**
   * 获取用户已获得和未获得的徽章分类统计
   * @param {number} userId - 用户ID（可选，不传则获取当前用户）
   */
  getBadgeStats: (userId) => {
    const badgePromise = userId ? 
      request(`/badge/user/${userId}`, 'GET') : 
      request('/badge/my-badges', 'GET');
    
    return badgePromise.then(res => {
      const badges = res.data || [];
      const obtained = badges.filter(badge => badge.obtained);
      const locked = badges.filter(badge => !badge.obtained);
      
      return {
        code: 200,
        data: {
          total: badges.length,
          obtained: obtained.length,
          locked: locked.length,
          obtainedBadges: obtained,
          lockedBadges: locked
        }
      };
    });
  }
};

module.exports = badgeAPI;
